import { useEffect, useState } from 'react';
import { Upload, Spin, message } from 'antd';
import type { UploadFile, UploadProps } from 'antd';
import { LoadingOutlined, PlusOutlined, DeleteOutlined } from '@ant-design/icons';
import { useCurrentComponent } from '../../../../hooks/useCurrentComponent';

type ImageUploadProps = {
    id: number;
    value?: UploadFile[];
    onChange?: (fileList: UploadFile[]) => void;
    name?: string;
    disabled?: boolean;
    maxSize?: number; // 单位MB
    allowedTypes?: string[];
};

const ImageUpload = (props: ImageUploadProps) => {
    const {
        id,
        // value = [],
        // onChange,
        name = 'image',
        disabled = true,
        maxSize = 2,
        allowedTypes = ['image/jpeg', 'image/png'],

    } = props;
    const [loading, setLoading] = useState(false);
    const [value, onChange] = useState<UploadFile[]>([])
    const { setCurComponentProps, currentElement } = useCurrentComponent();

    useEffect(() => {
        // console.log('c', value)
    }, [currentElement, value])


    const beforeUpload: UploadProps['beforeUpload'] = (file) => {
        const isAllowedType = allowedTypes.includes(file.type);
        if (!isAllowedType) {
            message.error(`只能上传 ${allowedTypes.join(', ')} 格式的文件`);
            return Upload.LIST_IGNORE;
        }

        const isLtMaxSize = file.size / 1024 / 1024 < maxSize;
        if (!isLtMaxSize) {
            message.error(`文件大小不能超过 ${maxSize}MB`);
            return Upload.LIST_IGNORE;
        }

        return true;
    };

    const handleChange: UploadProps['onChange'] = ({ file, fileList }) => {
        if (file.status === 'uploading') {
            setLoading(true);
        } else if (file.status === 'done') {
            setLoading(false);
            message.success(`${file.name} 上传成功`);
        } else if (file.status === 'error') {
            setLoading(false);
            message.error(`${file.name} 上传失败`);
        }
        setCurComponentProps({ ...currentElement?.props, upload: {...file}})
        // 直接调用父组件更新
        onChange?.(fileList);
    };

    const uploadButton = (
        <div>
            {loading ? <LoadingOutlined /> : <PlusOutlined />}
            <div className="mt-2">上传图片</div>
        </div>
    );

    return (
        <div className="relative">
            <Upload
                name={name}
                listType="picture-card"
                fileList={value}  // 直接使用props中的value
                beforeUpload={beforeUpload}
                onChange={handleChange}
                disabled={disabled}
                showUploadList={{
                    showRemoveIcon: !disabled,
                    removeIcon: <DeleteOutlined className="text-red-500 hover:text-red-700" />
                }}
                customRequest={({ file, onSuccess }) => {

                    // 模拟上传过程，实际替换为你的上传逻辑
                    setTimeout(() => {
                        onSuccess?.('ok');
                    }, 1500);
                }}
            >
                {value.length >= 1 ? null : uploadButton}
            </Upload>

            {loading && (
                <div className="absolute inset-0 bg-black bg-opacity-50 flex items-center justify-center">
                    <Spin indicator={<LoadingOutlined className="text-white" spin />} />
                </div>
            )}
        </div>
    );
};

export default ImageUpload;
